package com.wyp168.socket.tcp.socketDemo02;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 客户端
 */
@SuppressWarnings({"all"})
public class Client {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            socket = new Socket(InetAddress.getLocalHost(), 9000);
            outputStream = socket.getOutputStream();
            outputStream.write("hello sever!".getBytes());
            //设置结束标记
            socket.shutdownOutput();

            //获取和socket对象关联的输入流， 读取数据（字节），并显示
            byte[] buf = new byte[1024];
            int readLen = 0;
//            Thread.sleep(1000);
            inputStream = socket.getInputStream();
//            while (inputStream == null || inputStream.read(buf) == -1) {
//                inputStream = socket.getInputStream();
//            }
            while ((readLen = inputStream.read(buf)) != -1) {
                System.out.println(new String(buf, 0, readLen));
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                System.out.println("客户端 Socket对象资源关闭成功...");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}
